package com.t235.gc.gateway;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Component
public class RestTempUtils {
    private RestTemplate restTemplate = new RestTemplate();
    @Autowired
    private HttpServletRequest httpServletRequest;

    public <T> T getForObject(String url, Class<T> responseType) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.put(HttpHeaders.COOKIE, getSsoCookie());
        ResponseEntity<T> responseEntity = restTemplate.exchange(url, HttpMethod.GET,new HttpEntity(httpHeaders), responseType);
        return responseEntity.getBody();
    }

    public <T> T postForObject(String url, MultiValueMap requestParams, Class<T> responseType) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.put(HttpHeaders.COOKIE, getSsoCookie());
        HttpEntity<MultiValueMap> entity = new HttpEntity<>(requestParams, httpHeaders);
        ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, entity, responseType);
        return responseEntity.getBody();
    }

    public <T> T postForObject(String url, String jsonString, Class<T> responseType) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.put(HttpHeaders.COOKIE, getSsoCookie());
        HttpEntity<String> entity = new HttpEntity<>(jsonString, httpHeaders);
        ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, entity, responseType);
        return responseEntity.getBody();
    }
    public <T> T postForObject(String url, Class<T> responseType) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.put(HttpHeaders.COOKIE, getSsoCookie());
        ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, new HttpEntity(httpHeaders), responseType);
        return responseEntity.getBody();
    }

    public List<String> getSsoCookie() {
        Cookie[] cookies = httpServletRequest.getCookies();
        List<String> cookieList = new ArrayList<>();
        if(cookies != null) {
            for (Cookie cookie : cookies) {
                cookieList.add(cookie.getName() + "=" + cookie.getValue());
            }
        }
        return cookieList;
    }
}
